package com.hn.kiss.config.util;

import com.hn.kiss.config.common.MyException;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;

public class DownloadUtil {
    Logger logger = LoggerFactory.getLogger(DownloadUtil.class);

    /**
     * 文件下载到客户端
     * @param response
     * @param path 文件地址
     * @return
     * @throws UnsupportedEncodingException
     */
    public void download(HttpServletResponse response, String... path) throws MyException {
        for (String str : path) {
            download(response, str);
        }

    }

    /**
     * 文件下载到客户端
     * @param response
     * @param path
     * @throws MyException
     */
    public void download(HttpServletResponse response, String path) throws MyException {
        int index = path.lastIndexOf('/');
        String fileName = path.substring(index);
        FileInputStream inputStream = null;
        OutputStream outputStream = null;
        try{
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/force-download");
            fileName=new String(fileName.getBytes("gb2312"),"ISO8859-1");
            response.setHeader("Content-Disposition","attachment;filename=" + fileName);
            inputStream = new FileInputStream(path);
            outputStream = response.getOutputStream();
            IOUtils.copy(inputStream, outputStream);
        } catch(Exception e){
            logger.error("错误信息：{}",e.toString());
            throw new MyException("文件下载失败");
        }finally {
            IOUtils.closeQuietly(inputStream);
            IOUtils.closeQuietly(outputStream);
        }
    }
}
